package com.imay.live.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.imay.base.activity.BaseActivity;
import com.imay.live.activity.recharge.RechargeActivity;
import com.imay.live.adapter.SystemNoticeAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.heartlikeslib.swipelayout.SwipeHorizontalMenuLayout;
import com.imay.live.heartlikeslib.swipelayout.SwipeMenuRecyclerView;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.manager.UnreadManager;
import com.imay.live.model.SystemNoticeModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultNoData;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.DialogUtil;
import com.imay.live.utils.RecyclerViewUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.R;


import java.util.ArrayList;
import java.util.List;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * create by nick
 * 我的-->通知界面
 */
public class SystemNoticeActivity extends BaseActivity implements ProtoCallBack, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {


    private RecyclerView rcv_mine_notice;
    private String loadSystemNoticeCommand;
    private List<SystemNoticeModel> systemNoticeModels;
    private SystemNoticeAdapter systemNoticeAdapter;
    private String ignoreSystemNoticeCommand;
    private String deleteSystemNoticeCommand;
    private SystemNoticeModel noticeModel;

    public static void start(Context context) {
        context.startActivity(new Intent(context, SystemNoticeActivity.class));
    }

    public static void startActivityForResult(Activity context, int request) {
        context.startActivityForResult(new Intent(context, SystemNoticeActivity.class), request);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_system_notice;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setTitle(getString(R.string.mine_system_notice));
        rcv_mine_notice = $(R.id.rcv_system_notice);
        RecyclerViewUtil.setLinearLayoutManager(this, rcv_mine_notice);
        systemNoticeModels = new ArrayList<>();
        DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), "");
        loadSystemNotice();
        getTitleBar().addRightTextView(getString(R.string.system_notice_ignore_unread));
        getTitleBar().setRightTextOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (hasUnreadData()) {
                    ignoreUnread();
                    ToastUtil.show(SystemNoticeActivity.this, R.string.system_notice_ignore_toast2);
                } else {
                    ToastUtil.show(SystemNoticeActivity.this, R.string.system_notice_ignore_toast1);
                }
            }
        });
        MobclickAgent.onEvent(SystemNoticeActivity.this, "notice_open");
    }

    private void loadSystemNotice() {
        loadSystemNoticeCommand = ProtoRequestHelper.task(ProtoHttpFactory.getSystemNotice()).setTag(this.hashCode()).request(this);
    }


    @Override
    public void onRequestSuccess(String command, String data) {
        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
        if (data == null) {
            return;
        }
        if (command.equals(loadSystemNoticeCommand)) {
            Result<List<SystemNoticeModel>> listResult = JSON.parseObject(data, new TypeReference<Result<List<SystemNoticeModel>>>() {
            }.getType());
            if (listResult.result == CodeSuccess) {
                systemNoticeModels.addAll(listResult.data);
                bindAdapter();
            }
        } else if (command.equals(ignoreSystemNoticeCommand)) {
            Log.e("system_notice", data);
            try {
                ResultNoData result = JSON.parseObject(data, new TypeReference<ResultNoData>() {
                }.getType());
                if (result.result == CodeSuccess) {
                    ignoreLocalDataUnread();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (command.equals(deleteSystemNoticeCommand)) {
            ResultNoData result = JSON.parseObject(data, new TypeReference<ResultNoData>() {
            }.getType());
            if (result.result == CodeSuccess) {
                systemNoticeModels.remove(noticeModel);
                bindAdapter();
                if (!hasUnreadData()) {
                    UnreadManager.getInstance().postUnreadEvent(UnreadManager.TYPE_UNREAD_SYSTEM_PROFILE, 0);
                }
            }
        }

    }

    @Override
    public void onRequestError(String command, int code, String message) {
        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
    }

    private void bindAdapter() {
        if (systemNoticeAdapter == null) {
            systemNoticeAdapter = new SystemNoticeAdapter(systemNoticeModels);
            rcv_mine_notice.setAdapter(systemNoticeAdapter);
            View view = LayoutInflater.from(this).inflate(R.layout.view_load_layout, null);
            view.setVisibility(View.VISIBLE);
            systemNoticeAdapter.setEmptyView(view);
            systemNoticeAdapter.setOnItemClickListener(this);
            systemNoticeAdapter.setOnItemChildClickListener(this);
        } else {
            systemNoticeAdapter.setNewData(systemNoticeModels);
            systemNoticeAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        systemNoticeModels.get(position).setReaded();
        bindAdapter();
        if (!hasUnreadData()) {
            UnreadManager.getInstance().postUnreadEvent(UnreadManager.TYPE_UNREAD_SYSTEM_PROFILE, 0);
        }
        SystemNoticeDetailActivity.start(this, systemNoticeModels.get(position).getContentType());
        MobclickAgent.onEvent(SystemNoticeActivity.this, "notice_click");
    }

    private void ignoreUnread() {
        if (systemNoticeModels == null || systemNoticeModels.isEmpty()) return;
        List<Integer> integers = new ArrayList<>();
        for (SystemNoticeModel model : systemNoticeModels) {
            integers.add(model.getContentType());
        }
        ignoreSystemNoticeCommand = ProtoRequestHelper.task(ProtoHttpFactory.ignoreSystemNoticeUnread(integers)).setTag(this.hashCode()).request(this);


    }

    private void ignoreLocalDataUnread() {
        if (systemNoticeModels == null || systemNoticeModels.isEmpty()) return;
        for (SystemNoticeModel model : systemNoticeModels) {
            model.setIsRead(2);
            model.setUnReadNum(0);
        }
        bindAdapter();
        UnreadManager.getInstance().postUnreadEvent(UnreadManager.TYPE_UNREAD_SYSTEM_PROFILE, 0);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, final View view, final int position) {

        DialogUtil.getNormalDialog(this, getString(R.string.delete_warning), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SwipeHorizontalMenuLayout layout = (SwipeHorizontalMenuLayout) view.getParent().getParent();
                layout.smoothCloseMenu();
                noticeModel = systemNoticeModels.get(position);
                deleteSystemNotice(noticeModel.getContentType());
            }
        }).show();


    }

    private void deleteSystemNotice(int contentType) {
        DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), "");
        deleteSystemNoticeCommand = ProtoRequestHelper.task(ProtoHttpFactory.deleteSystemNotice(contentType)).setTag(this.hashCode()).request(this);
    }

    private boolean hasUnreadData() {
        if (systemNoticeModels == null || systemNoticeModels.isEmpty()) return false;
        {
            for (SystemNoticeModel model : systemNoticeModels) {
                if (!model.hasReaded()) {
                    return true;
                }
            }
        }
        return false;

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
